Page({
  data: {
    houseLayerVisible: false, // 控制选择房屋动作面板的显示/隐藏
    dateLayerVisible: false, // 控制访问日期动作面板的显示/隐藏
    houseList: [],

    currentDate: Date.now(),
    maxDate: Date.now() + 3 * 24 * 60 * 60 * 1000,

    houseInfo: '',

    houseId: '',
    name: '',
    gender: 1,
    mobile: '',
    visitDate: '',
  },

  onLoad() {
    this.getHouseList()
  },

  // 0. 获取审核通过的房屋
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/house')
    if (code !== 10000) return wx.utils.toast('获取房屋列表失败')
    this.setData({
      houseList,
    })
  },

  // 1. 选择房屋
  selectHouse(ev) {
    const { name: houseInfo, id: houseId } = ev.detail
    this.setData({
      houseInfo,
      houseId,
    })
  },

  // 2. 选择日期
  selectDate(ev) {
    this.setData({
      dateLayerVisible: false,
      visitDate: wx.utils.formatDate(ev.detail),
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },

  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },

  async submit() {
    const { houseId, name, gender, mobile, visitDate } = this.data
    // 1.1 数据校验
    if (!wx.utils.verifyHouse(houseId)) return
    if (!wx.utils.verifyName(name)) return
    if (!wx.utils.verifyMobile(mobile)) return
    if (!wx.utils.verifyDate(visitDate)) return
    // 1.2 发请求
    const { code, data } = await wx.http.post('/visitor', { houseId, name, gender, mobile, visitDate })
    if (code !== 10000) return wx.utils.toast('新增访客失败!')
    // console.log(data)
    // 1.3 跳转
    wx.reLaunch({
      url: `/visitor_pkg/pages/passport/index?id=${data.id}`,
    })
  },
})
